package lvcy.message.http;

import java.io.IOException;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;

public class HttpClientGenerator {

	private static HttpClientGenerator httpClientGenerator=new HttpClientGenerator();
	private PoolingHttpClientConnectionManager connectionManager;
	
	public static HttpClientGenerator getInstance(){
		if(httpClientGenerator==null){
			synchronized (httpClientGenerator) {
				httpClientGenerator=new HttpClientGenerator();
			}
		}
		return httpClientGenerator;
	}
	
	private HttpClientGenerator() {
		Registry<ConnectionSocketFactory> registry=RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", PlainConnectionSocketFactory.INSTANCE)
				.register("https", SSLConnectionSocketFactory.getSocketFactory())
				.build();
		connectionManager=new PoolingHttpClientConnectionManager(registry);
		connectionManager.setDefaultMaxPerRoute(100);
	}
	public void setPoolSize(int size){
		connectionManager.setDefaultMaxPerRoute(size);
	}
	public int getPoolSize(){
		return connectionManager.getDefaultMaxPerRoute();
	}
	public CloseableHttpClient getHttpClient(){
		
		HttpClientBuilder httpClientBuilder=HttpClients.custom().setConnectionManager(connectionManager);
		httpClientBuilder.setUserAgent("");
		httpClientBuilder.addInterceptorFirst(new CustomHttpRequestInterception());
		httpClientBuilder.setDefaultSocketConfig(getSocketConfig());
		httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
		httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
		return httpClientBuilder.build();
	}
	private SocketConfig getSocketConfig(){
		return SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
	}
	
	
	private class CustomHttpRequestInterception implements HttpRequestInterceptor{

		public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
			if(!request.containsHeader("Accept-Encoding")){
				request.addHeader("Accept-Encoding","gzip");
			}
		}
		
	}
	
}
